var Validate = require("COMMON/Components/Validator/v1.0");
var Pagination = require("COMMON/modules/pagination-x/v1.0");
var Select = require("COMMON/modules/select/index.1.0");
var MemberList = require("./tpl/index.xtpl");
var AddUserModal = require("./tpl/adduser.xtpl");
var IdNumBox = require("./tpl/idnumbox.xtpl");
var ImgUploador = require("../mem");
var Member = ZFT.Util.Class({
    container: $("body"),
    EVENTS: {
        "click #newBtn": "showUserForm",
        "change #addNewTel": "checkPhone",
        "change #addUserType": "changeUserProp",
        "change #userProp": "toggleIdOrLicense"
    },
    validator: {},
    init: function () {
        var that = this;
        var schBtn = $("#schUserType");
        var pagination;

        that.getList(1);
        that.loadAddUser();
        schBtn.on("click", function () {
            that.getList(1);
        });
        pagination = this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, topage: toPage });
            that.getList(toPage);
        });

        that.container.on("click", ".close,.cancel", function (e) {
            that.closeModal(e);
        });

    },
    loadAddUser: function () {
        var pers = ZFT.Util.getPermission(),
            addBtn = '<button id="newBtn" class="m-btn m-btn_ol_default">新建用户</button>';
        $("#addBox").html(($.inArray("37", pers) !== -1) && addBtn);
    },
    //关闭模态框
    closeModal: function (e) {
        var tarBtn = $(e.currentTarget);
        tarBtn.parents(".m-modal_bg").fadeOut(200);
    },
    //初始化图片上传插件
    initImgUpload: function (i) {
        var uploadorname = $("#imgLoaderContainer_" + i).find("input[name=callback]").val();
        if (uploadorname) {
            uploadorname = uploadorname.split(".")[0];
            window[uploadorname] = new ImgUploador({ container: $("#imgLoaderContainer_" + i) });
        }
    },

    //显示新建用户modal
    showUserForm: function (e) {
        var _this = this;
        var render = ZFT.Util.ParseTemplate(AddUserModal);
        var dtype = ZFT.Util.getDtype();
        var html = render({ data: dtype });
        $("#modal").html(html);
        setTimeout(function () {
            $("#addNewTel,#addNewPwd").val("").css("background-color", "#fff");;
            $("input:-webkit-autofill").css("-webkit-box-shadow", "0 0 0 1000px white inset");
        }, 500);
        _this.initImgUpload("hd_1");
        // _this.getBankList();
        _this.render();
        $("#addBtn").on("click", function () {
            _this.onFormSubmit();
        })
    },
    // 显示租户的性质 0:个人 1:企业
    changeUserProp: function () {
        var _this = this;
        var idNumBox = $("#idNumBox");
        var render = ZFT.Util.ParseTemplate(IdNumBox);
        var html;
        var userType = {
            userType: 0
        }
        html = render({ data: userType });
        $("#userProp").val(0);
        idNumBox.html(html);


    },
    //租户性质变化的时候,显示营业执照或身份证
    toggleIdOrLicense: function (e) {
        var idNumBox = $("#idNumBox");
        var render = ZFT.Util.ParseTemplate(IdNumBox);
        var tarOp = $(e.currentTarget);
        var tarVal = tarOp.val();
        var idbox;
        var optt = {
            userType: tarVal
        }
        idbox = render({ data: optt });
        idNumBox.html(idbox);


    },
    //初始化校验
    render: function () {
        var that = this;
        setTimeout(function () {
            that.validator["dname"] = that.validateDname();
            that.validator["mobile"] = that.validateTel();
            that.validator["addr"] = that.validateAddr();
            //that.validator["idcard"] = that.validateId();
            //that.validator["bankCard"] = that.validateBankCard();
            //that.validator["acc"] = that.validateAcc();
            that.validator["accpwd"] = that.validateAccPwd();
        }, 10);
    },
    //获取会员列表
    getList: function (toPage) {
        var that = this;
        var paramType = $("#paramType").val();
        var paramValue = $("#searchInp").val();
        var userType = $("#userType").val();
        var tbody = $("#tbody");
        var page = $("#paginationWrap");
        var cnt = page.attr("data-cnt");
        var pageSize = page.attr("data-size");
        if (!cnt) cnt = 0;
        if (!toPage) toPage = 1;
        if (!paramValue) paramValue = '';
        ZFT.Util.Ajax(
            "/r/member_index",
            {
                type: "POST",
                dataType: "json",
                params: {
                    "paramValue": paramValue,
                    "paramType": paramType,
                    "userType": userType,
                    "page": toPage,
                    "page_size": pageSize ? pageSize : 15

                },
                loading: function () {
                    var html = '<tr id="yhglLoad"><td colspan="6">加载中,请稍后...</td></tr>'
                    tbody.html(html);
                    page.hide();
                },
                success: function (res) {

                    var html = '';
                    var data = res.data;
                    var list = data.list;
                    var msg = res.msg;
                    var render = ZFT.Util.ParseTemplate(MemberList);
                    if (res.code == 200) {
                        if (list.length <= 0) {
                            tbody.html('<tr><td colspan="6">暂无数据</td></tr>');
                            page.hide();
                            return false;
                        }
                        var html = render({ memberArr: list });
                        tbody.html(html);
                        that.pagination.render({ current: toPage, topage: toPage, total: data.total });
                        //  page.attr("data-cnt", data.cnt);
                    } else if (res.code = 102) {
                        var html = '<tr><td colspan="6">' + msg + '</td></tr>';
                        tbody.html(html);
                    } else {
                        var html = '<tr ><td colspan="6">' + msg + '</td></tr>';
                        tbody.html(html);
                    }
                }
            })
    },
    addUser: function () {
        var that = this;
        var header = $("#addNewHeader").val();
        var userType = $("#userProp").val();
        var formData = {
            dtype: $("#addUserType").val(),
            nickname: $("#addNewName").val(),
            mobile: $("#addNewTel").val(),
            address: $("#addNewAddr").val(),
            id_card: $("#addNewIdNum").val(),
            password: $("#addNewPwd").val(),
        };
        if (formData["dtype"] == 2) {
            if (!formData["id_card"] && userType == 1) return ZFT.Util.STip("fail", "请输入营业执照!");
            formData["user_type"] = userType;
        } else {
            if (!formData["id_card"]) return ZFT.Util.STip("fail", "请输入身份证号!");
        }
        if (header) formData["header"] = header;
        ZFT.Util.Ajax("/r/member_add", {
            type: "POST",
            dataType: "json",
            params: formData,
            success: function (res) {
                var msg = res.msg;
                if (res.code == 200) {
                    var dtype = $("#addUserType").val();
                    //console.log(dtype)
                    $("#userType").val(dtype);
                    $("#modal").html("");
                    that.getList(1);
                    ZFT.Util.STip("success", msg, 3000);
                } else if (res.code == 102) {
                    return ZFT.Util.STip("fail", "未登录,请重新登录", 4000, function () {
                        window.location.href = "/index/index/login";
                    });
                } else {
                    return ZFT.Util.STip("fail", msg, 3000);
                }
            }
        })
    },

    //手机号检测
    checkPhone: function (e) {
        var that = this;
        var telInp = $(e.currentTarget);
        var tel = telInp.val();
        var tip = telInp.siblings(".tip");
        var reg = new RegExp('^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$');
        if (reg.test(tel)) {
            $.ajax({
                url: "/r/member_checkMobile",
                type: "POST",
                dataType: "json",
                data: {
                    mobile: tel
                },
                success: function (res) {
                    switch (res.code) {
                        case 200:
                            tip.text("可以注册").removeClass("error");
                            break;
                        case 203:
                            tip.text(res.msg).addClass("error");
                    }
                }
            })
        }
    },
    //验证手机号
    validateTel: function () {
        var telInp = $("#addNewTel");
        var that = this;
        return Validate({
            target: telInp,
            event: 'blur',
            rule: ["require", "mobile"],
            callback: function (rule, isOk, errMsg, errCode, target, value) {
                var tip = target.siblings(".tip");
                if (isOk) {
                    tip.text("").removeClass("error");
                } else {
                    tip.addClass("error").text(errMsg);
                }
            }
        })
    },
    //验证身份证
    validateId: function () {
        var idInp = $("#addNewIdNum");
        var that = this;
        return Validate({
            target: idInp,
            event: 'blur',
            rule: ["require"],
            callback: function (rule, isOk, errMsg, errCode, target, value) {
                var tip = target.siblings(".tip");
                if (isOk) {
                    tip.text("");
                } else {
                    tip.addClass("error").text(errMsg);
                }
            }
        })
    },

    //验证用户姓名
    validateDname: function () {
        var dnameInp = $("#addNewName");
        return Validate({
            target: dnameInp,
            event: "blur",
            rule: ["require"],
            callback: function (rule, isOk, errMsg, errCode, target, value) {
                var tip = target.siblings(".tip");
                if (isOk) {
                    tip.text("");
                } else {
                    tip.addClass("error").text(errMsg);
                }
            }
        });
    },
    //获取银行列表
    getBankList: function () {
        var that = this;
        var bank_inp = $("#addNewBank");
        var select = new Select({
            source: "/index/bankCode.html",
            ajaxType: "POST",
            ajaxParams: {
            },
            isFillContent: false,
            filterType: "ajax",  //指定过滤方式为ajax
            field: {
                id: "id",
                name: "title",
            },
            trigger: $("#addNewBank"),
            filter: false,
            adaptor: function (res) {
                $(".selectOptionUl").css("padding-left", 0);
                var reslut = { code: 200 };
                var list = res.data.list;
                if (!list) {
                    return reslut;
                }
                var newList = [];
                for (var i = 0; i < list.length; i++) {
                    list[i].id = list[i].code;
                    list[i].title = list[i].bank;
                    newList.push(list[i]);
                }
                reslut["data"] = newList;
                return reslut;
            },
        });
    },

    //验证地址
    validateAddr: function () {
        var addrInp = $("#addNewAddr");
        return Validate({
            target: addrInp,
            event: "blur",
            rule: ["require"],
            callback: function (rule, isOk, errMsg, errCode, target, value) {
                var tip = target.siblings(".tip");
                if (isOk) {
                    tip.text("");
                } else {
                    tip.addClass("error").text(errMsg);
                }
            }
        })
    },


    //验证平台密码
    validateAccPwd: function () {
        var pwdInp = $("#addNewPwd");
        return Validate({
            target: pwdInp,
            event: "blur",
            rule: ["require"],
            callback: function (rule, isOk, errMsg, errCode, target, value) {
                var tip = target.siblings(".tip");
                if (isOk) {
                    tip.text("");
                } else {
                    tip.addClass("error").text(errMsg);
                }
            }
        })
    },
    onFormSubmit: function (e) {
        var that = this;
        var validator = this.validator;
        //var tarBtn = $(e.currentTarget);
        //var tip = $("#addNewTel").siblings(".tip");
        var canSubmit = true;
        for (var i in validator) {
            var valid = validator[i];
            if (typeof valid == "function") {
                var result = valid();
                if (!result.isOk) {
                    canSubmit = false;
                    break;
                }
            }
        }
        if (!canSubmit) return ZFT.Util.STip("fail", "请检查是否有未填项!");
        that.addUser();
    }


});
$(function () {
    new Member();
})